package com.jsj.subway.ai.utils;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@Component
@ServerEndpoint(value = "/wss-alarm-message")
public class NotifyServer {
    
    private Session session;
    private static CopyOnWriteArraySet<NotifyServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
 　　* 连接建立后触发的方法
　　 */
    @OnOpen 
    public void onOpen(Session session){
        this.session = session;
        log.info("onOpen"+session.getId());
        webSocketSet.add(this);
    }

    /**
 　　* 连接关闭后触发的方法
 　　*/
    @OnClose
    public void onClose(){
        //从map中删除
        webSocketSet.remove(this);
        log.info("====== onClose:" + session.getId() + " ======");
     
    }

    /**
　　 * 接收到客户端消息时触发的方法
　　 */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("Received message: " + message);
        for (NotifyServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
　　 * 发生错误时触发的方法
 　　*/
    @OnError
    public void onError(Session session,Throwable error){
        log.error("wss 发生错误：:{}:{}",session.getId(),error.getMessage());
        error.printStackTrace();
    }
    public synchronized void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public synchronized void sendMessage(int status,String message,Object datas) throws IOException{
        JSONObject result = new JSONObject();
        result.put("status", status);
        result.put("message", message);
        result.put("datas", datas);
        this.session.getBasicRemote().sendText(result.toString());
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

}